package com.lx.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

//springboot中shiro的配置类
@Configuration

public class ShiroConfig {
    //创建Realm对象
    @Bean
    public UserRealm getUserRealm(){
        return new UserRealm();
    }
    //创建DefaultWebSecurityManager
    @Bean(name = "getDefaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //设置Realm
        defaultWebSecurityManager.setRealm(getUserRealm());
        return defaultWebSecurityManager;
    }
    //创建ShiroFilterFactoryBean
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());

        Map<String, String> filterChainDefinitionMap = new HashMap<>();
        //设置/user/* 路径的过滤规则
        filterChainDefinitionMap.put("/user/*","authc");

        //设置/user/add路径的过滤规则，没有user：add则认证失败
        filterChainDefinitionMap.put("/user/add","perms[user:add]");
        filterChainDefinitionMap.put("/user/update","perms[user:update]");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        //设置权限拦截后，向登录页面跳转
        shiroFilterFactoryBean.setLoginUrl("/toLogin");

        //设置未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/unAuth");

        return shiroFilterFactoryBean;
    }

    //整合ShiroDialect方言（和thymeleaf 整合）
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
